import useBrandInfo from "@/common/hook/useBrandInfo"
import { useUserStore } from "@/common/hox/userStore"
import { getUserCouponList } from "@/service"
import { useRequest } from "ahooks"
import { createGlobalStore } from "hox"
import { useMemo } from "react"

// 电影票优惠券列表，仅用于展示
export const [useCouponStore, getCouponStore] = createGlobalStore(() => {
  const { brandInfo: movieBrandInfo } = useBrandInfo()
  const movieBrandId = useMemo(() => movieBrandInfo && movieBrandInfo.id, [movieBrandInfo])
  const { userInfo } = useUserStore()

  const getCouponApi = useRequest(async () => {
    return (await getUserCouponList({})).list
      .filter(item => (item.brandId === 0 || item.brandId === movieBrandId) && item.batchValue)
      .sort((a, b) => b.batchValue - a.batchValue)
  }, {
    ready: Boolean(movieBrandId && userInfo?.userId),
    // 用户信息改变时（绑定手机号），会导致资产合并，这里重新查询优惠券列表
    refreshDeps: [userInfo]
  })

  return {
    movieCouponList: getCouponApi.data || [],
    refreshCoupon: getCouponApi.refresh
  }
})
